import vlc
from PyQt6.QtCore import QObject, pyqtSignal, QTimer

def format_time(milliseconds):
    """将毫秒格式化为 HH:MM:SS"""
    if milliseconds < 0: milliseconds = 0
    seconds = milliseconds // 1000
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return f"{hours:02d}:{minutes:02d}:{seconds:02d}"

class PlayerCore(QObject):
    """封装VLC播放器核心逻辑，并通过信号与UI通信"""
    playback_state_changed = pyqtSignal(bool)
    position_changed = pyqtSignal(int)
    time_changed = pyqtSignal(str)
    media_ended = pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.instance = vlc.Instance("--no-xlib")
        self.player = self.instance.media_player_new()

        event_manager = self.player.event_manager()
        event_manager.event_attach(vlc.EventType.MediaPlayerPlaying, lambda e: self.playback_state_changed.emit(True))
        event_manager.event_attach(vlc.EventType.MediaPlayerPaused, lambda e: self.playback_state_changed.emit(False))
        event_manager.event_attach(vlc.EventType.MediaPlayerStopped, lambda e: self.playback_state_changed.emit(False))
        event_manager.event_attach(vlc.EventType.MediaPlayerEndReached, self._on_media_ended)

        self.player.video_set_mouse_input(False)
        self.player.video_set_key_input(False)

        self._timer = QTimer(self)
        self._timer.setInterval(200)
        self._timer.timeout.connect(self._update_ui_signals)

    def play_media(self, filepath):
        media = self.instance.media_new(filepath)
        self.player.set_media(media)
        self.player.play()
        self._timer.start()

    def play_pause(self):
        if self.player.is_playing():
            self.player.pause()
        else:
            if self.player.get_media():
                self.player.play()

    def stop(self):
        self.player.stop()
        self._timer.stop()

    def set_volume(self, volume):
        return self.player.audio_set_volume(volume)

    def get_volume(self):
        return self.player.audio_get_volume()

    def set_position(self, position):
        self.player.set_position(position)

    def seek_relative(self, offset_ms):
        if not self.player.is_seekable():
            return

        current_time = self.player.get_time()
        new_time = current_time + offset_ms

        self.player.set_time(new_time)

    def set_hwnd(self, win_id):
        self.player.set_hwnd(win_id)

    def is_playing(self):
        return self.player.is_playing()

    def _update_ui_signals(self):
        position = self.player.get_position()
        self.position_changed.emit(int(position * 1000))

        current_time = self.player.get_time()
        total_time = self.player.get_length()
        time_str = f"{format_time(current_time)} / {format_time(total_time)}"
        self.time_changed.emit(time_str)

    def _on_media_ended(self, event):
        self._timer.stop()
        self.playback_state_changed.emit(False)
        self.media_ended.emit()